const redis = require('redis')

const redis_config = {
    host: '192.168.20.130',
    port: '6379',
    password: '11111111',
    number: 0,
}

const url = `redis://:${redis_config.password}@${redis_config.host}:${redis_config.port}/${redis_config.number}`

const redisClient = redis.createClient({'url': url})

redisClient.on('ready', () => {
    console.log('redis is ready...')
})

redisClient.on('error', err => {
    console.error(err)
})

async function exec(callback, key, value, expireIn){
    return new Promise(async (res, rej) => {
        await redisClient.connect()     // 连接
        let ok = callback(key, value, expireIn)   // 成功ok
        try {
            res(ok)
            await redisClient.quit()        // 关闭
        }catch (err){
            console.log('error=',err.message)
            rej(err)
            await redisClient.quit()        // 关闭
        }
    })
}

const redisDB = {
    async set(key, value, expireIn){
        return exec(async () => {
            if (expireIn === undefined || expireIn === null){
                return await redisClient.set(key, value)
            }
            expireIn = parseInt(expireIn, 10)
            // 设置键名为 "key" 的值并指定过期时间 expireIn（单位为秒）
            await redisClient.setEx(key, expireIn, value)
        }, key, value, expireIn)
    },
    async get(key){
        return exec(async () => {
            return await redisClient.get(key)
        }, key)
    },
    async del(key){
        return exec(async () => {
            return await redisClient.del(key)
        }, key)
    },
    async getTtl(key){
        return exec(async() => {
            return await redisClient.ttl(key)
        }, key)
    },
    getVal: (key) =>{
        return new Promise((resolve, reject)=>{
            redisClient.get(key)
            .then(res => resolve(res))
            .catch(err => reject(err))
        })
    },
}

module.exports = {
    redisDB
}